import Request from '@/utils/luch-request/index.js' // 下载的插件

const baseURL = process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:8000/api/' : 'https://www.greeting.ink/api/';

const http = new Request();

/**
 * @description 修改全局默认配置
 * @param {Function}   
*/
http.setConfig((config) => { /* config 为默认全局配置*/
	//根域名
	config.baseURL = baseURL
	
	//后端需要加次参数判断ajax请求
	config.header = {
		'X-Requested-With': 'XMLHttpRequest',
	}
	
	// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
	// 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
	config.custom = {
		token: true,
		loading: true,
	}
	 
	//响应时间
	config.timeout = 30000
	
	return config
});

//在请求之前拦截
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	//解构header数据
	config.header = {
		...config.header
	}
	
	//获取本地存储的token
	let token = uni.getStorageSync('token');
	if (token) {
		config.header.Authorization = `Bearer ${token}`;
	}

	if (config.custom.loading) {
		uni.showToast({icon: 'loading'})
	}

    //演示： 如果token不存在，return Promise.reject(config) 会取消本次请求

	return config
}, config => { 
	// 可使用async await 做异步操作
	return Promise.reject(config)
})

//在请求之后拦截
/* 对响应成功做点什么 可使用async await 做异步操作*/
http.interceptors.response.use((response) => { 
	//对响应错误做点什么 （statusCode == 200）
	uni.hideLoading();
	const code = response.data.code;
	const data = response.data.data;

	if (code !== 200) {
		return Promise.reject(res.msg);
	}
	
	return Promise.resolve(data);
	
}, (response) => { 
	//对响应错误做点什么 （statusCode !== 200）
	uni.hideLoading();
	const statusCode = response.statusCode;
	const errMsg = response.errMsg;
	const code = response.data.code;
	const data = response.data.data;
	
	// HTTP级别状态码
	if (statusCode === 500) {
		uni.showToast({
			title: '服务器无法响应',
			duration: 3000,
			icon: 'error',
		})
	} else if (statusCode === 404) {
		uni.showToast({
			title: 'API地址错误',
			duration: 3000,
			icon: 'error',
		})
	} else if (statusCode === 403) {
		uni.showToast({
			title: '无权访问',
			duration: 3000,
			icon: 'error',
		})
	} else{
		uni.showToast({
			title: errMsg,
			duration: 3000,
			icon: 'error',
		})
	}
	return Promise.reject(response)
})


//构建请求类
class HttpFactory {
	constructor(method, api, data = {}, loading = true){
		this.method = method;
		this.api = api;
		this.data = data;
		this.loading = loading;
	}
	
	exec() {
		return new Promise((resolve, reject) => {
			if (this.method === 'get') {
				http.get(this.api, {params: this.data}).then(res => {
					resolve(res)
				}).catch(err => {
					console.log('HttpFactory.exec',err);
				})
				return false;
			}
			
			const methods = ['post', 'put', 'delete'];
			
			if (methods.includes(this.method)) {
				http[this.method](this.api, this.data ).then(res => {
					resolve(res)
				}).catch(err => {
					console.log('HttpFactory.exec',err);
				})
				return false;
			}
			
		});
	}
}


const get = (api, data = {}, loading = false) => (new HttpFactory('get', api, data, loading)).exec();

const post = (api, data = {}, loading = true) => (new HttpFactory('post', api, data, loading)).exec();

const put = (api, data = {}, loading = true) => (new HttpFactory('put', api, data, loading)).exec();

const remove = (api, data = {}, loading = true) => (new HttpFactory('delete', api, data, loading)).exec();

export {
	get,
	post,
	put,
	remove,
}